 /**
 * 计算两个字符串之间的Levenshtein距离
 * @param {string} str1 字符串1
 * @param {string} str2 字符串2
 * @returns {number} Levenshtein距离
 */
export function levenshteinDistance(str1, str2) {
    const m = str1.length;
    const n = str2.length;
    const d = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));

    for (let i = 0; i <= m; i++) {
        d[i][0] = i;
    }

    for (let j = 0; j <= n; j++) {
        d[0][j] = j;
    }

    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
            d[i][j] = Math.min(
                d[i - 1][j] + 1, // 删除
                d[i][j - 1] + 1, // 插入
                d[i - 1][j - 1] + cost // 替换
            );
        }
    }

    return d[m][n];
}

/**
 * 将Levenshtein距离转换为相似度（0到1之间）
 * @param {string} str1 字符串1
 * @param {string} str2 字符串2
 * @returns {number} 相似度
 */
export function levenshteinSimilarity(str1, str2) {
    const distance = levenshteinDistance(str1, str2);
    const maxLength = Math.max(str1.length, str2.length);
    return 1 - distance / maxLength;
}

